﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.AppCode.Lib;

namespace mojoPortal.Web.RS.Controls
{
    public partial class ModalManagePermissionControl : RSBaseUserControl
    {


        protected void Page_Load(object sender, EventArgs e)
        {


        }

        //private void SendEmail(string body, string subject, string fromEmail, string toEmail)
        //{
        //    System.Net.Mail.MailMessage eMail = new System.Net.Mail.MailMessage();
        //    eMail.IsBodyHtml = true;
        //    eMail.Body = body;
        //    eMail.From = new System.Net.Mail.MailAddress(fromEmail);
        //    eMail.To.Add(toEmail);
        //    eMail.Subject = subject;
        //    System.Net.Mail.SmtpClient SMTP = new System.Net.Mail.SmtpClient();

        //    string smtpUserName = ConfigurationManager.AppSettings["SMTPUser"].ToString();
        //    string smtpPassword = ConfigurationManager.AppSettings["SMTPPassword"].ToString();
        //    string smtpServer = ConfigurationManager.AppSettings["SMTPServer"].ToString();
        //    SMTP.Credentials = new System.Net.NetworkCredential(smtpUserName, smtpPassword);
        //    SMTP.Host = smtpServer;
        //    SMTP.Send(eMail);
        //    eMail.Dispose();
        //    lblManagePermissionHeader.Text = "Thank you.  Registration email has been sent.";
        //    btnSendRegistrationNotification.Enabled = false;
        //}

        protected void btnSendRegistrationNotification_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            string body = "Registration for ReadyService:  <br/><br/>" +
                "URL: " + ConfigurationManager.AppSettings["ReadyServiceRegistrationURL"].ToString() + "<br/>" +
                "Employee ID: " + lblEmployeeID.Text + "<br/>" +
                "Registration PIN: " + txtPIN.Text + "<br/>" +
                "Company Name: " + userIdentity.RSCompanyName;
             
            string subject = "Registration for ReadyService";
            string toEmail = lblEmail.Text;
            string fromEmail = userIdentity.RSUserEmail;
            if (fromEmail.Length > 0 && toEmail.Length > 0)
                RSCommonFunctions.SendEmail(body, subject, fromEmail, toEmail);
        }
        public void ShowModalManagePermission(int companyid, int EmployeeID)
        {
            LoadGroupListRDL(companyid);
            LoadEmployeePermissionData(companyid, EmployeeID);
            btnSavePermission.Enabled = true;
            lblPINMessage.Text = "";
            lblManagePermissionHeader.Text = "Manage User Permission";
            mpeModalManagePermission.Show();
        }

        protected void btnModalOK_Click(Object sender, EventArgs e)
        {
            mpeModalManagePermission.Hide();
        }

        private void LoadGroupListRDL(int companyid)
        {
            SqlCommand myCommand;
            SqlDataReader myDataReader;
            String sqlSELECT = "select groupid, groupname from rs_tblGroup where companyID=@companyid order by groupname asc";
            SqlParameter param = new SqlParameter();
            SqlConnection myConnection;

            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(sqlSELECT, myConnection);
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);
            myConnection.Open();

            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            rdlEmployeeGroup.Items.Clear();
            rdlEmployeeGroup.DataSource = myDataReader;
            rdlEmployeeGroup.DataTextField = "groupname";
            rdlEmployeeGroup.DataValueField = "groupid";
            rdlEmployeeGroup.DataBind();
            myConnection.Close();
        }

        private void LoadEmployeePermissionData(int companyid, int EmployeeID)
        {
            if (companyid > 0 && EmployeeID > 0)
            {
                String strSQL = "select firstname, lastname, email, enablelogin, isactive, pin, groupid, isgrouplead, canread, canwrite, candelete, companyid from rs_tblEmployee where EmployeeID=@EmployeeID and companyid=@companyid";
                SqlCommand myCommand;
                SqlParameter param;
                SqlConnection myConnection;
                myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
                myCommand = new SqlCommand(strSQL, myConnection);
                SqlDataReader myDataReader;
                param = new SqlParameter();
                param.SqlDbType = SqlDbType.Int;
                param.ParameterName = "@EmployeeID";
                param.Value = EmployeeID;
                myCommand.Parameters.Add(param);

                param = new SqlParameter();
                param.SqlDbType = SqlDbType.Int;
                param.ParameterName = "@companyid";
                param.Value = companyid;
                myCommand.Parameters.Add(param);

                myConnection.Open();
                myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                if (myDataReader.HasRows)
                {
                    myDataReader.Read();
                    lblEmployeeID.Text = EmployeeID.ToString();
                    lblFirstName.Text = myDataReader["FirstName"].ToString();
                    lblLastName.Text = myDataReader["LastName"].ToString();
                    lblEmail.Text = myDataReader["Email"].ToString();

                    txtPIN.Text = myDataReader["PIN"].ToString();
                    if (myDataReader["EnableLogin"] != DBNull.Value)
                    {
                        chkEnableLogin.Checked = Convert.ToBoolean(myDataReader["EnableLogin"].ToString());
                    }

                    if (myDataReader["IsActive"] != DBNull.Value)
                    {
                        chkIsActive.Checked = Convert.ToBoolean(myDataReader["IsActive"].ToString());
                    }

                    if (myDataReader["IsGroupLead"] != DBNull.Value)
                    {
                        chkIsGroupLead.Checked = Convert.ToBoolean(myDataReader["IsGroupLead"].ToString());
                    }

                    if (myDataReader["GroupId"] != DBNull.Value)
                    {
                        if(Convert.ToInt32(myDataReader["GroupId"].ToString()) > 0)
                            rdlEmployeeGroup.SelectedValue = myDataReader["GroupId"].ToString();
                    }

                    if (myDataReader["CanRead"] != DBNull.Value)
                    {
                        if (Convert.ToBoolean(myDataReader["CanRead"].ToString()) == true)
                            chkCanRead.Checked = true;
                    }
                    if (myDataReader["CanWrite"] != DBNull.Value)
                    {
                        if (Convert.ToBoolean(myDataReader["CanWrite"].ToString()) == true)
                            chkCanWrite.Checked = true;
                    }
                    if (myDataReader["CanDelete"] != DBNull.Value)
                    {
                        if (Convert.ToBoolean(myDataReader["CanDelete"].ToString()) == true)
                            chkCanDelete.Checked = true;
                    }
                }
                myConnection.Close();
            }
        }

        protected void btnSavePermission_Click(object sender, EventArgs e)
        {
            bool enablelogin = chkEnableLogin.Checked;
            bool isactive = chkIsActive.Checked;
            bool isgrouplead = chkIsGroupLead.Checked;
            string PIN = txtPIN.Text.Trim();
            bool canread = chkCanRead.Checked;
            bool canwrite = chkCanWrite.Checked;
            bool candelete = chkCanDelete.Checked;
            int groupid = 0;
            if(rdlEmployeeGroup.SelectedItem != null)
                groupid = Convert.ToInt32(rdlEmployeeGroup.SelectedValue);

            int selectedEmployeeID = Convert.ToInt32(lblEmployeeID.Text);
            RSUserIdentity userIdentity = GetRSUserIdentity();
            SqlCommand sqlCmd = new SqlCommand();

            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@PIN", SqlDbType.NVarChar, 15, ParameterDirection.Input, PIN);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@IsActive", SqlDbType.Bit, 0, ParameterDirection.Input, isactive);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@EnableLogin", SqlDbType.Bit, 0, ParameterDirection.Input, enablelogin);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CanRead", SqlDbType.Bit, 0, ParameterDirection.Input, canread);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CanWrite", SqlDbType.Bit, 0, ParameterDirection.Input, canwrite);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CanDelete", SqlDbType.Bit, 0, ParameterDirection.Input, candelete);
            if(groupid > 0)
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@GroupId", SqlDbType.Int, 0, ParameterDirection.Input, groupid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@IsGroupLead", SqlDbType.Bit, 0, ParameterDirection.Input, isgrouplead);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@EmployeeID", SqlDbType.Int, 0, ParameterDirection.Input, selectedEmployeeID);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, userIdentity.RSCompanyId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, userIdentity.RSCurrentUser);
            SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSaveEmployeePermission");
            SQLHelper.ExecuteScalarCmd(sqlCmd);

            int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
            if (returnValue == -1)
            {
                lblManagePermissionHeader.ForeColor = System.Drawing.Color.Red;
                lblManagePermissionHeader.Text = "PIN already assigned to someone else.  Please create a different PIN.";
            }
            else
            {
                lblManagePermissionHeader.ForeColor = System.Drawing.Color.DarkBlue;
                lblManagePermissionHeader.Text = "Permission Successfully Saved!";
                btnSavePermission.Enabled = false;
            }
        }

        protected void btnCheckPIN_Click(object sender, EventArgs e)
        {
            int EmployeeID;
            string PIN;
            PIN = txtPIN.Text.Trim();
            EmployeeID = lblEmployeeID.Text == "" ? 0 : Convert.ToInt32(lblEmployeeID.Text);
            if (PIN.Length > 0 && EmployeeID > 0)
            {
                SqlCommand sqlCmd = new SqlCommand();

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@PIN", SqlDbType.NVarChar, 15, ParameterDirection.Input, PIN);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@EmployeeID", SqlDbType.Int, 0, ParameterDirection.Input, EmployeeID);


                SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspCheckPIN");
                SQLHelper.ExecuteScalarCmd(sqlCmd);

                int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                if (returnValue == -1)
                {
                    lblPINMessage.Text = "PIN already assigned to someone else.  Please use a different PIN.";
                    lblPINMessage.ForeColor = System.Drawing.Color.Red;
                }
                else
                {
                    lblPINMessage.Text = "PIN is available.";
                    lblPINMessage.ForeColor = System.Drawing.Color.Blue;
                }
            }
            else
            {
                lblPINMessage.Text = "Please create a PIN.";
                lblPINMessage.ForeColor = System.Drawing.Color.Red;
            }
        }
    }
}